<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="仓库名称" prop="storeName">
        <el-input v-model="queryParams.storeName" placeholder="请输入仓库名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="仓库编码" prop="storeCode">
        <el-input v-model="queryParams.storeCode" placeholder="请输入仓库编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input v-model="queryParams.equipmentName" placeholder="请输入监控设备名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备编码" prop="equipmentCode">
        <el-input v-model="queryParams.equipmentCode" placeholder="请输入监控设备编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="仓位名称" prop="storeLocationName">
        <el-input v-model="queryParams.storeLocationName" placeholder="请输入仓库名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="仓位编码" prop="storeLocationCode">
        <el-input v-model="queryParams.storeLocationCode" placeholder="请输入仓位编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="指令类型" prop="commandType" width="120">
        <template slot-scope="scope">
          <el-select v-model="queryParams.commandType" placeholder="启用自动巡检" :onSelectionChange="handleQuery" clearable>
            <el-option v-for="dict in dict.type.platform_command_type" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="执行状态" prop="commandExecutionStatus" width="120">
        <template slot-scope="scope">
          <el-select v-model="queryParams.commandExecutionStatus" placeholder="启用自动巡检" :onSelectionChange="handleQuery"
            clearable>
            <el-option v-for="dict in dict.type.platform_command_execution_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="预警状态" prop="warningStatus" width="120">
        <template slot-scope="scope">
          <el-select v-model="queryParams.warningStatus" placeholder="预警状态" :onSelectionChange="handleQuery" clearable>
            <el-option v-for="dict in dict.type.platform_warning_status" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="指令执行时间" prop="commandExecuteTimeRange">
        <div class="block">
          <el-date-picker v-model="queryParams.commandExecuteTimeRange" type="datetimerange"
            format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            align="right">
          </el-date-picker>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-s-promotion" size="mini" @click="handleAdd"
          v-hasPermi="['platform:command:add']">发送指令</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['platform:command:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['platform:command:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['platform:command:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commandList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="仓位名称" width="150" align="center" prop="storeLocationName" :show-overflow-tooltip="true" />
      <el-table-column label="仓位编码" width="80" align="center" prop="storeLocationCode" />
      <el-table-column label="设备名称" width="80" align="center" prop="equipmentName" :show-overflow-tooltip="true" />
      <el-table-column label="设备编码" width="80" align="center" prop="equipmentCode" />
      <el-table-column label="仓库名称" width="80" align="center" prop="storeName" />
      <el-table-column label="指令类型" width="120" align="center" prop="commandType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.platform_command_type" :value="scope.row.commandType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="执行状态" width="100" align="center" prop="commandExecutionStatus"
        :show-overflow-tooltip="true"> -->
      <el-table-column label="执行结果状态" width="100" align="center" prop="commandResultExecutionStatus"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.platform_command_execution_status"
            :value="scope.row.commandResultExecutionStatus" />
        </template>
      </el-table-column>
      <el-table-column label="执行时间" align="center" prop="commandExecuteTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.commandExecuteTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="重试次数" width="80" align="center" prop="retryCount" />
      <el-table-column label="预警状态" width="80" align="center" prop="warningStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.platform_warning_status" :value="scope.row.warningStatus" />
        </template>
      </el-table-column>
      <el-table-column label="仓位状态" width="80" align="center" prop="inspectionStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.platform_location_status" :value="scope.row.inspectionStatus" />
        </template>
      </el-table-column>
      <el-table-column label="货物数量" width="80" align="center" prop="inspectionQuantity" />
      <el-table-column label="巡检人" align="center" prop="inspectionOperator" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['platform:command:edit']">查看</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['platform:command:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改【执行指令】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="发送指令仓位：" prop="storeLocationId">
          <el-select v-model="form.storeLocationId" filterable remote reserve-keyword :remote-method="loadLocationList"
            @change="loadComandEquipment" placeholder="请输入监控设备名称或编码进行搜索" :loading="initData.loading"
            style="width: 500px">
            <el-option v-for="item in initData.locationList" :key="item.storeLocationId" :label="item.storeLocationName"
              :value="item.storeLocationId">
              <span style="float: left">{{ item.storeLocationCode }}</span>
              <span style="
                float: right;
                color: var(--el-text-color-secondary);
                font-size: 13px;
              ">
                {{ item.storeLocationName }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <div>
          <template :loading="this.initData.loading">
            <el-row>
              <el-col :span="12">
                <el-form-item label="仓位启用状态：" prop="locationUseStatus">
                  <el-switch v-model="this.initData.commandLocation.useStatus" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备启用状态：" prop="equipmentUseStatus">
                  <el-switch v-model="this.initData.commandEquipment.useStatus" :active-value="1" :inactive-value="0" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="设备编码：" prop="equipmentCode">
                  <el-input v-model="this.initData.commandEquipment.equipmentCode" placeholder="监控设备编码" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备名称：" prop="equipmentIp">
                  <el-input v-model="this.initData.commandEquipment.equipmentName" placeholder="监控设备IP" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="设备IP：" prop="equipmentCode">
                  <el-input v-model="this.initData.commandEquipment.equipmentIp" placeholder="监控设备IP" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备通道：" prop="equipmentChannel" disabled>
                  <el-input v-model="this.initData.commandEquipment.equipmentChannel" placeholder="监控设备通道" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="指令类型：" prop="commandType">
              <template>
                <el-radio-group v-model="form.commandType" size="medium">
                  <el-radio border label="dict.label" v-for="dict in dict.type.platform_command_type" :label="dict.value"
                    :value="dict.label">{{ dict.label }}</el-radio>
                  <!-- <el-radio-button v-for="dict in dict.type.platform_command_type" :label="dict.label"
                    :value="dict.value" /> -->
                </el-radio-group>
              </template>
            </el-form-item>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--查看详情对话框 -->
    <el-dialog title="查看指令详情" :close="cancelDteail" :visible.sync="viewCommandObj.open" width="800px" append-to-body>
      <div v-loading="viewCommandObj.loading">
        <el-form label-width="120px" v-if="!viewCommandObj.loading">
          <el-row>
            <el-col :span="12" tyle="height: 50px;">
              <el-form-item label="仓位名称：" :show-overflow-tooltip="true">
                <el-text class="mx-1" size="large"> {{ this.viewCommandObj.data.location.storeLocationCode }}</el-text>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓位编码：" prop="equipmentChannel" :show-overflow-tooltip="true">
                <el-text class="mx-1" size="large"> {{ this.viewCommandObj.data.location.storeLocationName }}</el-text>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="水平初始角：" :show-overflow-tooltip="true">
                <el-text class="mx-1" size="large"> {{ this.viewCommandObj.data.location.pan }}</el-text>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="初始垂直角：" :show-overflow-tooltip="true">
                <el-text class="mx-1" size="large"> {{ this.viewCommandObj.data.location.tilt }}</el-text>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备名称：" :show-overflow-tooltip="true">
                <el-text class="mx-1" size="large"> {{ this.viewCommandObj.data.equipment.equipmentName }}</el-text>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备编码：" prop="equipmentChannel" :show-overflow-tooltip="true">
                <el-text class="mx-1" size="large"> {{ this.viewCommandObj.data.equipment.equipmentCode }}</el-text>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备IP：" :show-overflow-tooltip="true">
                <el-text class="mx-1" size="large"> {{ this.viewCommandObj.data.equipment.equipmentIp }}</el-text>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备通道：" :show-overflow-tooltip="true">
                <el-text class="mx-1" size="large"> {{ this.viewCommandObj.data.equipment.equipmentChannel }}</el-text>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="仓位启用状态：" :show-overflow-tooltip="true">
                <el-switch v-model="this.viewCommandObj.data.location.useStatus" :active-value="1" :inactive-value="0"
                  disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备启用状态：" :show-overflow-tooltip="true">
                <el-switch v-model="this.viewCommandObj.data.equipment.useStatus" :active-value="1" :inactive-value="0"
                  disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="指令类型：" :show-overflow-tooltip="true">
                <dict-tag :options="dict.type.platform_command_type" :value="this.viewCommandObj.data.commandType" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="指令执行状态：" :show-overflow-tooltip="true">
                <dict-tag :options="dict.type.platform_command_execution_status"
                  :value="this.viewCommandObj.data.executeCommandResult.executionStatus" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="指令内容：">
            <el-input v-model="this.viewCommandObj.data.commandContent" type="textarea" placeholder="指令执行内容" disabled />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="执行开始时间：" :show-overflow-tooltip="true">
                {{ parseTime(this.viewCommandObj.data.executeCommandResult.executeStartTime, '{y}-{m}-{d} {h}:{i}:{s}')
                }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行结束时间：" :show-overflow-tooltip="true">
                {{ parseTime(this.viewCommandObj.data.executeCommandResult.executeEndTime, '{y}-{m}-{d} {h}:{i}:{s}')
                }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="执行结果：">
            <el-input v-model="this.viewCommandObj.data.commandContent" type="textarea" placeholder="执行执行结果" disabled />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" v-if="!viewCommandObj.loading">
        <el-button icon="el-icon-s-promotion" v-if="this.viewCommandObj.data.executeCommandResult.executionStatus > 1"
          type="primary" @click="retrySendCommand">重
          试</el-button>
        <el-button @click="cancelDteail" icon="el-icon-back">返 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCommand, getCommand, getResultCommand, delCommand, addCommand, updateCommand, retryCommand } from "@/api/platform/command"
import { listLocation, getLocation } from "@/api/platform/location"
import { getEquipment } from "@/api/platform/equipment"
import moment from 'moment';

export default {
  name: "Command",
  dicts: ['sys_normal_disable', 'platform_command_execution_status', 'platform_command_type', 'platform_warning_status', 'platform_location_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【执行指令】表格数据
      commandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //弹框下拉选择框数据
      initData: {
        loading: true,
        locationList: [],
        commandEquipment: { useStatus: null },
        commandLocation: { useStatus: null }
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentId: null,
        storeLocationId: null,
        storeLocationName: null,
        storeLocationCode: null,
        commandType: null,
        commandContent: null,
        commandExecuteTime: null,
        commandExecutionStatus: null,
        retryCount: null,
        warningStatus: null,
        inspectionStatus: null,
        inspectionQuantity: null,
        inspectionOperator: null,
        commandExecuteTimeRange: null,
        executeStartTime: null,
        executeEndTime: null,
      },
      // 表单参数
      form: {},
      // 查看时执行指令对象
      viewCommandObj: {
        open: false,
        item: null,
        loading: true,
        data: {
          location: {},
          loading: true,
          equipment: {},
          executeCommandResult: {}
        }
      },
      // 表单校验
      rules: {
        storeLocationId: [
          { required: true, message: "仓位ID不能为空", trigger: "change" }
        ],
        commandType: [
          { required: true, message: "请选择一个指令类型", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询【执行指令】列表 */
    getList() {
      this.loading = true
      if (Array.isArray(this.queryParams.commandExecuteTimeRange)) {
        this.queryParams.executeStartTime = moment(this.queryParams.commandExecuteTimeRange[0]).format('YYYY-MM-DD HH:mm:ss')
        this.queryParams.executeEndTime = moment(this.queryParams.commandExecuteTimeRange[1]).format('YYYY-MM-DD HH:mm:ss')
      }
      listCommand(this.queryParams).then(response => {
        this.commandList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancelDteail() {
      this.viewCommandObj.open = false
      this.viewCommandObj.loading = true
    },
    // 表单重置
    reset() {
      this.form = {
        commandId: null,
        equipmentId: null,
        equipmentCode: null,
        equipmentName: null,
        equipmentChannel: null,
        storeLocationId: null,
        storeLocationCode: null,
        locationUseStatus: null,
        equipmentUseStatus: null,
        commandType: null,
        commandContent: null,
        commandExecuteTime: null,
        commandExecutionStatus: null,
        retryCount: null,
        warningStatus: null,
        inspectionStatus: null,
        inspectionQuantity: null,
        inspectionOperator: null,
        commandExecuteTimeRange: null,
        executeStartTime: null,
        executeEndTime: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.commandId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "发送【执行指令】"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const commandId = row.commandId || this.ids
      getCommand(commandId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "查看【执行指令】"
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewCommandObj.loading = true
      this.viewCommandObj.open = true
      const queryParams = {
        commandId: row.commandId,
        commandResultId: row.commandResultId
      }
      getResultCommand(queryParams).then(response => {
        this.viewCommandObj.data = response.data
        this.viewCommandObj.loading = false
      })
    },
    /**重试指令**/
    retrySendCommand() {
      console.log(this.viewCommandObj.data)
      const data = {
        commandId: this.viewCommandObj.data.commandId,
        commandResultId: this.viewCommandObj.data.executeCommandResult.commandResultId
      }
      const obj = this.viewCommandObj
      this.$modal.confirm('是否确认重新发送指令？').then(function () {
        return retryCommand(data)
      }).then(() => {
        this.getList()
        obj.open = false
        this.$modal.msgSuccess("指令重新发送成功")
      }).catch((er) => {
        console.log(1, er)
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        const commandEquipment = this.initData.commandEquipment
        const commandLocation = this.initData.commandLocation
        if (commandEquipment !== null) {
          if (commandEquipment.useStatus === 0) {
            this.$message({
              message: '设备状态为未启用，不能执行指令',
              type: 'warning'
            });
            return
          } else {
            this.form.equipmentId = commandEquipment.equipmentId
          }
        }
        if (commandLocation !== null) {
          if (commandLocation.useStatus === 0) {
            this.$message({
              message: '仓位状态为未启用，不能执行指令',
              type: 'warning'
            });
            return
          } else {
            this.form.storeLocationCode = commandLocation.storeLocationCode
          }
        }
        if (valid) {
          if (this.form.commandId != null) {
            updateCommand(this.form).then(response => {
              this.$modal.msgSuccess("指令发送成功")
              this.open = false
              this.getList()
            })
          } else {
            addCommand(this.form).then(response => {
              this.$modal.msgSuccess("指令重发成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const commandIds = row.commandId || this.ids
      this.$modal.confirm('是否确认删除【执行指令】编号为"' + commandIds + '"的数据项？').then(function () {
        return delCommand(commandIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('platform/command/export', {
        ...this.queryParams
      }, `command_${new Date().getTime()}.xlsx`)
    },
    loadLocationList(key) {
      this.initData.loading = true
      const locationQueryParams = {
        key: key,
        useStatus: 1
      }
      listLocation(locationQueryParams).then(response => {
        this.initData.locationList = response.rows
        this.initData.loading = false
      })
    },
    loadComandEquipment(id) {
      const item = this.initData.locationList.find(i => i.storeLocationId === id)
      if (item != null) {
        this.initData.commandLocation = item
        getEquipment(item.equipmentId).then(response => {
          this.initData.commandEquipment = response.data
        })
      }
    }
  }
}
</script>
